package com.alstudio.utils.android;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.alstudio.ui.base.BaseActivity;
import com.alstudio.ui.module.image.crop.CropImage;
import com.alstudio.utils.android.imageProcess.ALImageProcessParams;
import com.alstudio.utils.android.imageProcess.ALImageProcessUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.toast.MyToastUtil;

/**
 * 多媒体工具类。提供播放音频、录制音频、拍照、选择照片、查看照片、截取图片功能
 * 
 * @author alonso lee
 * 
 */
public class AndroidMultiMediaUtils {

	// take a video
	private static final int ACTION_TAKE_VIDEO = 3;
	// take a photos
	public static final int ACTION_TAKE_PHOTOS = 4;
	// select a photos
	public static final int ACTION_SELECT_PHOTOS = 5;
	// crop image
	public static final int ACTION_CROP_PHOTOS = 6;

	// 目标:增加多媒体工具类。提供播放音频、录制音频、拍照、选择照片、查看照片、截取图片功能；

	// 图片输出目录
	private final static String IMAGE_DIR = "alonso/images/";

	// 裁剪输出的图片名的前缀
	private static final String CROP_JPEG_FILE_PREFIX = "CROP_";
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";

	public static String TEMP_TAKE_PHOTO_FILE_PATH = Environment
			.getExternalStorageDirectory() + File.separator + IMAGE_DIR;

	private static String mCurrentPhotoPath;

	/**
	 * 检测存储设备是否可用
	 * 
	 * @return true表示存储设备可用
	 */
	private static boolean checkExtStorageAvailable() {
		if (ALSdcardManager.isExtStorageAvailable()) {
			return true;
		}

		MyToastUtil.showToastOnTop("那个啥不可用", 2000);
		return false;
	}

	/**
	 * 创建缺省图片文件
	 * 
	 * @return
	 * @throws IOException
	 */
	private static File createImageFile() throws IOException {
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = new File(TEMP_TAKE_PHOTO_FILE_PATH);

		if (!albumF.exists()) {
			ALLog.d("Create the path:" + TEMP_TAKE_PHOTO_FILE_PATH);
			albumF.mkdirs();
		}

		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
				albumF);
		return imageF;
	}

	/**
	 * 创建指定路径指定前缀的图片文件
	 * 
	 * @param path
	 * @param prefix
	 * @return
	 * @throws IOException
	 */
	private static File createImageFile(final String path, final String prefix)
			throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = prefix + timeStamp + "_";
		File albumF = new File(path);

		if (!albumF.exists()) {
			ALLog.d("Create the path:" + path);
			albumF.mkdirs();
		}

		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
				albumF);
		return imageF;
	}

	private static File setUpPhotoFile() throws IOException {

		File f = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();
		return f;
	}

	public static String getImagePath() {
		return mCurrentPhotoPath;
	}

	public static void resetImagePath() {
		mCurrentPhotoPath = null;
	}

	/**
	 * 处理拍照请求
	 * 
	 * @param act
	 */
	public static void dispatchTakePictureIntent(BaseActivity act) {

		if (!checkExtStorageAvailable()) {
			return;
		}

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File f = null;
		try {
			f = setUpPhotoFile();
			mCurrentPhotoPath = f.getAbsolutePath();
			takePictureIntent
					.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		} catch (IOException e) {
			e.printStackTrace();
			f = null;
			mCurrentPhotoPath = null;
		}
		act.startActivityForResult(takePictureIntent, ACTION_TAKE_PHOTOS);
	}

	/**
	 * 处理录像请求
	 * 
	 * @param act
	 */
	public static void dispatchTakeVideoIntent(BaseActivity act) {

		if (!checkExtStorageAvailable()) {
			return;
		}

		Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		act.startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
	}

	/**
	 * 处理选择图片请求
	 * 
	 * @param act
	 */
	public static void dispatchSelectPhotos(BaseActivity act) {

		if (!checkExtStorageAvailable()) {
			return;
		}

		Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
		innerIntent.setType("image/*"); // 查看类型
		Intent wrapperIntent = Intent.createChooser(innerIntent, null);
		act.startActivityForResult(wrapperIntent, ACTION_SELECT_PHOTOS);
	}

	/**
	 * 处理裁剪图片请求
	 * 
	 * @param act
	 * @param param
	 */
	public static void dispatchCropPhotos(BaseActivity act,
			ALImageProcessParams param) {

		if (!TextUtils.isDigitsOnly(param.getRequestHeight() + "")) {
			throw new IllegalArgumentException("requestHeight param error!");
		}

		if (!TextUtils.isDigitsOnly(param.getRequestWidth() + "")) {
			throw new IllegalArgumentException("requestWidth param error!");
		}

		if (TextUtils.isEmpty(param.getImagePath())) {
			throw new IllegalArgumentException("image path param error!");
		}

		if (TextUtils.isEmpty(param.getSavePath())) {
			throw new IllegalArgumentException("save image path param error!");
		}

		if (!checkExtStorageAvailable()) {
			return;
		}

		Intent intent1 = new Intent(act, CropImage.class);
		intent1.putExtra("aspectX", 1);
		intent1.putExtra("aspectY", 1);
		intent1.putExtra("outputX", param.getRequestWidth());
		intent1.putExtra("outputY", param.getRequestHeight());
		intent1.putExtra("return-data", false);

		File parent = new File(param.getSavePath());

		// 创建文件夹
		if (!parent.exists()) {
			parent.mkdirs();
		}

		// 存放在头像文件夹
		File f = null;
		try {
			f = createImageFile(param.getSavePath(), CROP_JPEG_FILE_PREFIX);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		intent1.putExtra("image-path", param.getImagePath());
		intent1.putExtra("save_path", f.getPath());
		intent1.putExtra("scale", true);

		act.startActivityForResult(intent1, ACTION_CROP_PHOTOS);
	}

	/**
	 * 后台裁剪图片
	 * 
	 * @param act
	 * @param param
	 * @return
	 */
	public static String cropPhotosInExplicitCrop(BaseActivity act,
			ALImageProcessParams param) {

		try {
			File f = createImageFile(param.getSavePath(), CROP_JPEG_FILE_PREFIX);
			param.setSavePath(f.getAbsolutePath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ALImageProcessUtils.cropImage(act, param);
	}

	/**
	 * 显示图片处理对话框
	 * 
	 * @param ctx
	 * @param isSystemDialog
	 * @param param
	 */
	public static void showPhotoProcessDialog(BaseActivity ctx,
			boolean isSystemDialog, ALImageProcessParams param) {
		String[] items = new String[] { "拍照", "选择" };
		final AlertDialogCreator dialog = AlertDialogCreator
				.createOneButtonWithListItemDialog(ctx, isSystemDialog, items);
//		dialog.setTitle("选择操作选择操作选择操作选择操作选择操作选择操作选择操作选择操作选择操作选择操作选择操作选择操作选择操作");
		dialog.showDialog();
	}
}
